package api

import (
	"fmt"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"go_api/pkg/app"
	"go_api/pkg/e"
	"go_api/pkg/util"
	"go_api/pkg/weapp"
	"go_api/service/auth_service"
	"go_api/service/user_service"
	"go_api/service/wechat_service"
	"net/http"
	"strings"
)

type Params struct {
	Code string
}

func Authorization(c *gin.Context) {
	appG := app.Gin{C: c}
	valid := validation.Validation{}
	code := c.PostForm("code")
	a := Params{Code: code}
	ok, _ := valid.Valid(&a)
	if !ok {
		app.MarkErrors(valid.Errors)
		appG.ErrorResponse(http.StatusBadRequest, e.GetMsg(e.INVALID_PARAMS))
		return
	}
	isSuccess, str := weapp.GetWeAppOpenId(code)
	if !isSuccess {
		appG.ErrorResponse(http.StatusBadRequest, str)
		return
	}
	chatService := wechat_service.WeChat{WeappOpenId: str}
	err, chat := chatService.GetWeChat()
	fmt.Println("chat => 111", chat)
	if err != nil {
		appG.ErrorResponse(http.StatusInternalServerError, e.GetMsg(e.ERROR))
		return
	}

	if !(chat.ID > 0) {
		appG.Response(http.StatusOK, gin.H{
			"errCode": "noBindStudent",
		})
		return
	}
	authService := auth_service.Auth{UID: chat.UID}
	err, auth := authService.GetOneMember()

	if err != nil {
		appG.ErrorResponse(http.StatusInternalServerError, e.GetMsg(e.ERROR))
		return
	}

	if !(auth.UID > 0) {
		appG.Response(http.StatusOK, gin.H{
			"errCode": "noBindStudent",
		})
		return
	}
	userService := user_service.User{UID: auth.UID}
	err, user := userService.CheckUserUID()

	if err != nil {
		appG.ErrorResponse(http.StatusInternalServerError, e.GetMsg(e.ERROR))
		return
	}
	token, err := util.GenerateToken(auth.Username, auth.Password, auth.Role, auth.UID, user.ID)
	if err != nil {
		appG.ErrorResponse(http.StatusInternalServerError, e.GetMsg(e.ERROR_AUTH_TOKEN))
		return
	}
	appG.Response(http.StatusOK, gin.H{
		"access_token": token,
		"username": auth.Username,
		"uid": auth.UID,
		"role": strings.ToLower(auth.Role),
		"openid": str,
		"nickName": chat.Nickname,
		"avatarUrl": chat.Avatar,
	})
}
